package com.amkai.aes.webservice.binary.objecthandler;


import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.amkai.aes.aescommon.service.binary.job.RADBeanUniquePropertyJob;
import com.amkai.aes.webservice.binary.JobObjectHandler;
import com.amkai.rad.designerbase.beans.RADBean;
import com.amkai.common.extensions.hibernate.config.SiteManager;
import com.amkai.common.extensions.hibernate.config.manager.SessionManager;

public class RADBeanUniquePropertyHandler implements JobObjectHandler<RADBeanUniquePropertyJob, RADBean, RADBean> {

	private static final Log log = LogFactory.getLog(RADBeanUniquePropertyHandler.class);

	private String propertyValue;
	private String property;
	private String beanName;
	
	private String generateHQL(){
		return "SELECT o FROM " + beanName + " o WHERE o." + property + " = '" + propertyValue + "'";
	}
	
	@Override
	public RADBean process(RADBeanUniquePropertyJob job, RADBean object) throws Exception {

		RADBean result = null;
		try {
			property = job.getProperty();
			propertyValue = job.getPropertyValue();
			beanName = job.getClazz().getName();
			
			if (!property.equals("")) {
				
				SessionManager sm = SiteManager.Start();
				result = (RADBean)sm.execute(generateHQL()).uniqueResult();
			}
			
		} catch (Exception e) {
			log.error("",e);
			throw e;
		}
		
		return result;
	}


}
